package com.innerchic.huhu.http;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：watcher-demo
 * 日    期：2021/12/17 14:55
 * 包    名：com.innerchic.communication.http
 * 描    述：网络请求工具类
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
public class HttpRequest {

    private static final String TAG = "Watcher-http";

    /**
     * 同步get
     *
     * @param url 请求地址
     * @return 回调体
     */
    public static ResponseBody get(String url) {
        Log.d(TAG, "Get同步: " + url);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        ResponseBody body = null;
        try {
            Response response = call.execute();
            return response.body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * 异步get
     *
     * @param url      请求地址
     * @param callback 请求回调
     */
    public static void get(String url, HttpCallback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        //代理回调
        HttpCallbackProxy callbackProxy = new HttpCallbackProxy(url, callback);
        call.enqueue(callbackProxy);
    }

    /**
     * 同步post
     *
     * @param url         请求地址
     * @param requestBody 请求体
     */
    public static Response post(String url, String requestBody) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        String json = getJson(requestBody).toJSONString();
        Log.d(TAG, "Post同步: " + json);
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, json))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            return okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post异步
     *
     * @param url         请求地址
     * @param requestBody 请求体
     * @param callback    回调
     */
    public static void post(String url, String requestBody, HttpCallback callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        String json = getJson(requestBody).toJSONString();
        Log.d(TAG, "Post异步: " + json);
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, json))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        HttpCallbackProxy callbackProxy = new HttpCallbackProxy(url, callback);
        okHttpClient.newCall(request).enqueue(callbackProxy);
    }

    /**
     * 上传文件
     *
     * @param url      上传地址
     * @param file     文件对象
     * @param callback 回调
     */
    public static void upFile(String url, File file, HttpCallback callback) {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        Log.d(TAG, "upFile文件上传: " + (file == null ? "文件对象为null" : file.getName()));
        OkHttpClient okHttpClient = new OkHttpClient();
        if (file != null && file.exists()) {
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(mediaType, file))
                    .build();
            HttpCallbackProxy callbackProxy = new HttpCallbackProxy(url, callback);
            okHttpClient.newCall(request).enqueue(callbackProxy);
        }
    }

    /**
     * 上传文件
     *
     * @param url      上传地址
     * @param filePath 文件路径
     * @param callback 回调
     */
    public static void upFile(String url, String filePath, HttpCallback callback) {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();
        if (filePath == null) return;
        Log.d(TAG, "upFile文件上传: " + filePath);
        File file = new File(filePath);
        if (file.exists()) {
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(mediaType, file))
                    .build();
            HttpCallbackProxy callbackProxy = new HttpCallbackProxy(url, callback);
            okHttpClient.newCall(request).enqueue(callbackProxy);
        }
    }

    public static boolean loadApk(String url, String saveDir, String filename) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.body() == null) {
                return false;
            }
            InputStream is = null;//输入流
            FileOutputStream fos = null;//输出流
            try {
                is = response.body().byteStream();//获取输入流
                long total = response.body().contentLength();//获取文件大小
                if (new File(saveDir).mkdirs()) {
                    Log.d(TAG, "下载时创建了文件夹:" + saveDir);
                }
                File file = new File(saveDir, filename);//设置路径
                if (file.exists()) {
                    Log.d(TAG, "删除历史版本:" + file.delete());
                }
                fos = new FileOutputStream(file);
                int btMax = 1024 * 1024 * 10;
                byte[] buf = new byte[btMax];
                int ch;
                int process = 0;
                while ((ch = is.read(buf)) != -1) {
                    fos.write(buf, 0, ch);
                    process += ch;
                    final double pro = ((process * 1.0) / total) * 100;
                    fos.flush();
                    buf = new byte[btMax];
                }
            } catch (Exception e) {
                Log.d(TAG, "文件下载异常");
                e.printStackTrace();
                return false;
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "loadApk: 文件下载失败2");
            return false;
        }
    }

    /**
     * 获取Json
     */
    private static JSONObject getJson(String data) {
        if (data == null) return new JSONObject();
        JSONObject requestJson = new JSONObject();
        requestJson.put("data", data);
        return requestJson;
    }

}
